var NebPay = require("nebpay");
var nebPay = new NebPay();
var contractAddress = 'n21xUnbYd75fZ87XNsqxijKVapZK83MMj5H';
var apiUrl = 'https://mainnet.nebulas.io/v1/user/call';
var serialNumber;
var myaddress = 'n1xeM1FeyPUCyE7kG5ybkURiwgYHSHnV8in';

//to check if the extension is installed
//if the extension is installed, var "webExtensionWallet" will be injected in to web page
var isPhone = 0;
var loadIndex;
var matchData = {};
var intervalQuery;
var intervalBetQuery;
var txhash;
function toDecimal2(x) {
    if (isNaN(x)) {
        return false;
    }
    var f = Math.round(x*100)/100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    return s;
}
getWallectInfo();

window.onload = function () {
    var timestamp = Date.parse(new Date());
    var data = {};
    data.result = [];
    toastr.success('稍等，正在从星云链获取数据');
    toastr.success('如果数据显示不完全,可能是网络问题,劳请多次刷新页面');
    $.post(apiUrl, JSON.stringify({
        "from": myaddress,
        "to": contractAddress,
        "value": "0",
        "nonce": 1,
        "gasPrice": "1000000",
        "gasLimit": "200000",
        "contract": {"function": "getMatchInfo"}
    }), function (resp) {
        matchData = JSON.parse(resp.result.result);
        //过滤掉已过期比赛
        console.log(matchData.result);
        for(var i = 0;i < matchData.result.length;i ++)
        {
            if(matchData.result[i].startTime > (timestamp/1000) && matchData.result[i].status != 'closed')
            {
                data.result.push(matchData.result[i]);
            }

        }
        for(i = 0; i < data.result.length;i++)
        {
            data.result[i].startTime = timetrans(data.result[i].startTime);

        }
        for( i=0;i < data.result.length; i++){
            var home = parseFloat(data.result[i].homeAmount);
            var away = parseFloat(data.result[i].awayAmount);
            var draw = parseFloat(data.result[i].drawAmount);
            var total = home + away + draw;
            data.result[i].homeSp = toDecimal2(total/home ) || 0;
            data.result[i].awaySp = toDecimal2(total/away ) || 0;
            data.result[i].drawSp = toDecimal2(total/draw ) || 0;
            if(home <= 0)
                data.result[i].homeSp = 0;
            if(away <= 0)
                data.result[i].awaySp = 0;
            if(draw <= 0)
                data.result[i].drawSp = 0;
        }
        var tpl = $("#myTemplate").html();
        var template = Handlebars.compile(tpl);
        var html = template(data);
        $("#matchContainer").html(html);

    }, 'json');

    getUserInfo();
    getBetRecord();
    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
        isPhone = 1;
        $("#nav-title").css("font-size","30px");
        $(".bs-docs-header").css("text-align","center");
        $(".bs-docs-header, .bs-docs-masthead").css("padding","15px 0");
        $(".nav-slide").css("display","none");
        $("#phoneButton1").css("display","block");
        $("#phoneButton2").css("display","block");
        $("#self-info").css("display","none");

    }


};
function showBetModel(e) {
    // if(typeof(webExtensionWallet) === "undefined")
    // {
    //     $('#noWalletModel').modal('show');
    // }else {
        var choose = $(e).children('.btn-choose-type').text();
        var matchId = $(e).parents('.match-list-box').children('.matchID').text();
        for (var i = 0; i < matchData.result.length; i++) {
            if (matchData.result[i].id == matchId)
                var matchItem = matchData.result[i];
        }
        var homeName = matchItem.homeName;
        var awayName = matchItem.awayName;
        $('#betModel').modal('show');
        $('#betHomeName').html(homeName);
        $('#betAwayName').html(awayName);
        $('#betChoose').html(choose);
        $('#betMatchId').html(matchId);
    // }


}



function deposit() {
    $('#depositModel').modal('show');
}
function withdraw() {
    $('#withdrawModel').modal('show');
}

function funcIntervalCloseLoading() {
    layer.close(loadIndex);
}

function showLoading() {
    loadIndex = layer.load(0, {shade: [0.3,'#000']}); //0代表加载的风格，支持0-2
//loading层
    toastr.success('等待区块链确认消息!');
    intervalQuery = setInterval(function() {
        funcIntervalCloseLoading();
    }, 500); //建议查询频率10-15s,因为星云链出块时间为15s,并且查询服务器限制每分钟最多查询10次。

}




//得到插件中的钱包地址
function getWallectInfo() {
    window.postMessage({
        "target": "contentscript",
        "data": {},
        "method": "getAccount"
    }, "*");
    window.addEventListener('message', function (e) {
        if (e.data && e.data.data) {
            if (e.data.data.account) {//这就是当前钱包中的地址
                var address = e.data.data.account;
                if(address && address.length != 0){
                    myaddress = address;
                    console.log('my address:' + myaddress);

                }
            }
        }
    });
}
function getUserRecord() {
    $.post(apiUrl, JSON.stringify({
        "from": myaddress,
        "to": contractAddress,
        "value": "0",
        "nonce": 1,
        "gasPrice": "1000000",
        "gasLimit": "200000",
        "contract": {"function": "getAddressInfo"}
    }), function (resp) {
        var data = JSON.parse(resp.result.result);
        var balance = data.balance;
        balance = Math.floor(balance);
        var result = data.record || [];
        for(var i = 0; i < result.length;i++)
        {
            result[i].index = i + 1;
            result[i].time = timetrans(result[i].timestamp);
            result[i].amount = Math.floor(result[i].amount);

        }
        data.result = result;
        if(myaddress == "n1xeM1FeyPUCyE7kG5ybkURiwgYHSHnV8in")
        {
            $('#user-address').text("请安装星云钱包插件");
            $('#user-balance').text("0");

        }else{
            $('#user-address').text(myaddress);

            $('#user-balance').text(balance);

        }

        $('#user-infoModel').modal('show');

        var tpl = $("#recordTemplate").html();
        var template = Handlebars.compile(tpl);
        var html = template(data);
        $("#recordTable").html(html);

    }, 'json')
}

function getUserInfo() {
    if(typeof(webExtensionWallet) === "undefined")
    {
        var data = {};
        data.address = "请浏览教程安装星云链钱包插件!";
        data.balance = 0;
        $("#address").html(data.address);
        $("#balance").html(data.balance);

    }else {
        var arr = myaddress;
        if (arr.length >= 20) {
            arr = arr.substr(0, 8) + '....' + arr.substr(-8);
            var userAddress = arr;
        }
        $("#address").html(userAddress);
        $.post(apiUrl, JSON.stringify({
            "from": myaddress,
            "to": contractAddress,
            "value": "0",
            "nonce": 1,
            "gasPrice": "1000000",
            "gasLimit": "200000",
            "contract": {"function": "getSoccerBalance"}
        }), function (resp) {
            var balance = JSON.parse(resp.result.result) || 0;
            balance = Math.floor(balance)
            console.log(balance);
            $("#balance").html(balance);
        }, 'json')
    }

}
function getMatchInfo() {
    var timestamp = Date.parse(new Date());
    var data = {};
    data.result = [];
    $.post(apiUrl, JSON.stringify({
        "from": myaddress,
        "to": contractAddress,
        "value": "0",
        "nonce": 1,
        "gasPrice": "1000000",
        "gasLimit": "200000",
        "contract": {"function": "getMatchInfo"}
    }), function (resp) {
        matchData = JSON.parse(resp.result.result);
        //过滤掉已过期比赛
        console.log(matchData.result.length);
        for(var i = 0;i < matchData.result.length;i ++)
        {
            if(matchData.result[i].startTime > (timestamp/1000) && matchData.result[i].status != 'closed')
            {
                data.result.push(matchData.result[i]);
            }

        }
        for(i = 0; i < data.result.length;i++)
        {
            data.result[i].startTime = timetrans(data.result[i].startTime);

        }
        for( i=0;i < data.result.length; i++){
            var home = parseFloat(data.result[i].homeAmount);
            var away = parseFloat(data.result[i].awayAmount);
            var draw = parseFloat(data.result[i].drawAmount);
            var total = home + away + draw;
            data.result[i].homeSp = toDecimal2(total/home ) || 0;
            data.result[i].awaySp = toDecimal2(total/away ) || 0;
            data.result[i].drawSp = toDecimal2(total/draw ) || 0;
            if(home <= 0)
                data.result[i].homeSp = 0;
            if(away <= 0)
                data.result[i].awaySp = 0;
            if(draw <= 0)
                data.result[i].drawSp = 0;
        }
        var tpl = $("#myTemplate").html();
        var template = Handlebars.compile(tpl);
        var html = template(data);
        $("#matchContainer").html(html);

    }, 'json');

}
//时间戳转换
function timetrans(date1){
        var date = new Date(date1*1000);//如果date为10位不需要乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
        var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
        var m = (date.getMinutes() <10 ? '0' + date.getMinutes() : date.getMinutes()) ;
        var s = (date.getSeconds() <10 ? '0' + date.getSeconds() : date.getSeconds());
        return Y+M+D+h+m;
    }

function getAward() {
    showLoading();
    var to = contractAddress;   //Dapp的合约地址
    var value = "0";
    var callFunction = "getAward";  //调用的函数名称
    var callArgs =  "";   //参数格式为参数数组的JSON字符串, 比如'["arg"]','["arg1","arg2]'
    var options = {
        goods: {        //商品描述
            name: "example"
        },
        //callback 是交易查询服务器地址,
        //callback: NebPay.config.mainnetUrl //在主网查询(默认值)
        callback: NebPay.config.mainnetUrl, //在测试网查询
        listener: cbSendTx
    };
        if(isPhone == 1)
    {
        $('#getNasModel').modal('hide');

        $("#mobileTranModel").modal("show");
    }
    //发送交易(发起智能合约调用)
    serialNumber = nebPay.call(to, value, callFunction, callArgs, options);

}
//查询交易结果. queryPayInfo返回的是一个Promise对象.
function funcIntervalQueryGetAward() {
    // var options = {
    //     goods: {        //商品描述
    //         name: "example"
    //     }
    //     //callback 是交易查询服务器地址,
    //     //callback: NebPay.config.mainnetUrl //在主网查询(默认值)
    //     // callback: NebPay.config.mainnetUrl //在测试网查询
    // };

    //queryPayInfo的options参数用来指定查询交易的服务器地址,(如果是主网可以忽略,因为默认服务器是在主网查询)
    if(isPhone == 1)
    {
        nebPay.queryPayInfo(serialNumber)   //search transaction result from server (result upload to server by app)
            .then(function (resp) {
                console.log("tx result: " + resp);  //resp is a JSON string
                var respObject = JSON.parse(resp);
                //code==0交易发送成功, status==1交易已被打包上链
                if(respObject.code === 0 && respObject.data.status === 1){

                    toastr.success('交易已被区块链确认!');
                    clearInterval(intervalQuery);    //清除定时查询

                    // getUserInfo();
                    //交易成功,处理后续任务....
                }
                else if(respObject.code === 0 && respObject.data.execute_error != "")
                {
                    toastr.warning('交易返回错误!');
                    clearInterval(intervalQuery)    //清除定时查询

                }
            })
            .catch(function (err) {
                console.log(err);
                clearInterval(intervalQuery);
            });
    }
    else {
        $.post( 'https://mainnet.nebulas.io/v1/user/getTransactionReceipt', JSON.stringify({
            "hash": txhash
        }), function (respObject) {
            console.log(respObject.result.status);
            if(respObject.result.status === 1){

                toastr.success('交易已被区块链确认!');
                getUserInfo();
                //交易成功,处理后续任务....
                clearInterval(intervalQuery)    //清除定时查询
            }
            else if(respObject.result.status === 0)
            {
                toastr.warning('交易返回错误!');
                clearInterval(intervalQuery)    //清除定时查询

            }

        })
    }
}
function funcIntervalQueryGoBet() {
    // var options = {
    //     goods: {        //商品描述
    //         name: "example"
    //     }
    //     //callback 是交易查询服务器地址,
    //     //callback: NebPay.config.mainnetUrl //在主网查询(默认值)
    //     // callback: NebPay.config.mainnetUrl //在测试网查询
    // };

    //queryPayInfo的options参数用来指定查询交易的服务器地址,(如果是主网可以忽略,因为默认服务器是在主网查询)
    if(isPhone == 1) {
        nebPay.queryPayInfo(serialNumber)   //search transaction result from server (result upload to server by app)
            .then(function (resp) {
                console.log("tx result: " + resp);  //resp is a JSON string
                var respObject = JSON.parse(resp);
                //code==0交易发送成功, status==1交易已被打包上链
                if (respObject.code === 0 && respObject.data.status === 1) {

                    getMatchInfo();
                    // getUserInfo();
                    // getBetRecord();
                    toastr.success('投注已被区块链确认!');

                    //交易成功,处理后续任务....
                    clearInterval(intervalBetQuery)    //清除定时查询
                }
                else if (respObject.code === 0 && respObject.data.execute_error != "") {
                    toastr.warning('交易返回错误!');
                    clearInterval(intervalBetQuery)    //清除定时查询

                }
            })
            .catch(function (err) {
                console.log(err);
                clearInterval(intervalBetQuery);
            });
    }
    else {
        $.post( 'https://mainnet.nebulas.io/v1/user/getTransactionReceipt', JSON.stringify({
            "hash": txhash
        }), function (respObject) {
            console.log(respObject.result.status);
            if(respObject.result.status === 1){

                getMatchInfo();
                getUserInfo();
                // getBetRecord();
                toastr.success('投注已被区块链确认，2秒后刷新页面!');
                setTimeout("location.reload()","2000");
                //交易成功,处理后续任务....
                clearInterval(intervalBetQuery)    //清除定时查询
            }
            else if(respObject.result.status === 0)
            {
                toastr.warning('交易返回错误!');
                clearInterval(intervalBetQuery)    //清除定时查询

            }

        })
    }


}

function depositButton() {
    var amount = $('#depositAmount').val();
    var to = contractAddress;   //Dapp的合约地址
    var value = amount;
    var callFunction = "buySoccerCoin";  //调用的函数名称
    var callArgs =  "";   //参数格式为参数数组的JSON字符串, 比如'["arg"]','["arg1","arg2]'
    var options = {
        goods: {        //商品描述
            name: "example"
        },
        //callback 是交易查询服务器地址,
        //callback: NebPay.config.mainnetUrl //在主网查询(默认值)
        callback: NebPay.config.mainnetUrl, //在测试网查询
        listener: cbSendTx
    };
    if(isPhone == 1)
    {
        $('#depositModel').modal('hide');

        $("#mobileTranModel").modal("show");
    }
    //发送交易(发起智能合约调用)
    serialNumber = nebPay.call(to, value, callFunction, callArgs, options);

    //设置定时查询交易结果
    intervalQuery = setInterval(function() {
        funcIntervalQueryGetAward();
    }, 10000); //建议查询频率10-15s,因为星云链出块时间为15s,并且查询服务器限制每分钟最多查询10次。
}


function cbSendTx(resp){
    txhash = resp.txhash;
    console.log("callback resp: " + JSON.stringify(resp));
    layer.close(loadIndex);
    $('#betModel').modal('hide');
    document.getElementById("successId").innerText = resp.txhash;
    $('#tranSuccessModel').modal('show');

}
function withdrawButton() {
    var amount = $('#withdrawAmount').val();
    if(parseInt(amount) < 100)
        toastr.error('提现金额须大于100!');
    // showLoading();
    var to = contractAddress;   //Dapp的合约地址
    var value = "0";
    var callFunction = "withdraw";  //调用的函数名称
    var callArgs =  "[\"" + amount + "\"]";   //参数格式为参数数组的JSON字符串, 比如'["arg"]','["arg1","arg2]'
    var options = {
        goods: {        //商品描述
            name: "example"
        },
        //callback 是交易查询服务器地址,
        //callback: NebPay.config.mainnetUrl //在主网查询(默认值)
        callback: NebPay.config.mainnetUrl, //在测试网查询
        listener: cbSendTx
    };
    if(isPhone == 1)
    {
        $('#withdrawModel').modal('hide');

        $("#mobileTranModel").modal("show");
    }
    //发送交易(发起智能合约调用)
    serialNumber = nebPay.call(to, value, callFunction, callArgs, options);

    //设置定时查询交易结果
    intervalQuery = setInterval(function() {
        funcIntervalQueryGetAward();
    }, 10000); //建议查询频率10-15s,因为星云链出块时间为15s,并且查询服务器限制每分钟最多查询10次。
    console.log(amount);
}
function getBetRecord() {

    console.log("222"+myaddress);
    $.post(apiUrl, JSON.stringify({
        "from": myaddress,
        "to": contractAddress,
        "value": "0",
        "nonce": 1,
        "gasPrice": "1000000",
        "gasLimit": "200000",
        "contract": {"function": "getAddressGuessItem"}
    }), function (resp) {
        var data = JSON.parse(resp.result.result);
        console.log(data);
        for(var i=0;i < data.length; i++){

            if (data[i].txid.length >= 20) {
                data[i].txid = data[i].txid.substr(0, 8) + '....' + data[i].txid.substr(-8);
            }
            if(data[i].choose == 'Home')
                data[i].choose = '主胜';
            if(data[i].choose == 'Away')
                data[i].choose = '客胜';
            if(data[i].choose == 'Draw')
                data[i].choose = '平局';
        }
        var info = {};
        info.result = data;
        var tpl = $("#betScript").html();
        var template = Handlebars.compile(tpl);
        var html = template(info);
        $("#betInfo").html(html);


    }, 'json')


}
function goBetButton() {
    var amount = $('#bet-amount').val();
    if(parseInt(amount) < 100)
        toastr.error('竞猜金额须大于100!');
    else{
        var matchId = $('#betMatchId').text();
        var amount = $('#bet-amount').val();
        var choose = $('#betChoose').text();
        console.log(matchId);
        console.log(amount);
        console.log(choose);
        // showLoading();

        if(choose == "主胜")
            choose = "Home";
        if(choose == "客胜")
            choose = "Away";
        if(choose == "平局")
            choose = "Draw";

        var to = contractAddress;   //Dapp的合约地址
        var value = "0";
        var callFunction = "goGuess";  //调用的函数名称
        var callArgs =  "[\"" + matchId + "\" , \"" + amount + "\" , \"" + choose + "\"]";   //参数格式为参数数组的JSON字符串, 比如'["arg"]','["arg1","arg2]'
        console.log(callArgs);
        var options = {
            goods: {        //商品描述
                name: "example"
            },
            //callback 是交易查询服务器地址,
            //callback: NebPay.config.mainnetUrl //在主网查询(默认值)
            callback: NebPay.config.mainnetUrl, //在测试网查询
            listener: cbSendTx
        };
        //发送交易(发起智能合约调用)
        serialNumber = nebPay.call(to, value, callFunction, callArgs, {
            goods: {        //商品描述
                name: "example"
            },
            //callback 是交易查询服务器地址,
            //callback: NebPay.config.mainnetUrl //在主网查询(默认值)
            callback: NebPay.config.mainnetUrl, //在测试网查询
            listener: cbSendTx
        });
        if(isPhone == 1)
        {
            $('#betModel').modal('hide');

            $("#mobileTranModel").modal("show");
        }
        //设置定时查询交易结果
        intervalBetQuery = setInterval(function() {
            funcIntervalQueryGoBet();
        }, 10000); //建议查询频率10-15s,因为星云链出块时间为15s,并且查询服务器限制每分钟最多查询10次。
    }

}